<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>档位占比展示</title>
    <script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/html2canvas.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/saveImage.js') }}"></script>
    <style>
        /* body {
            background-image: url("{{ url_for('static', filename='img/bj.jpg') }}");
           
        } */

        /* 数据汇总卡片样式 */
        .dashboard {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .card {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .card-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .card-value {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .card-extra {
            font-size: 14px;
            color: #666;
        }

        .progress-bar {
            height: 8px;
            background: #f0f0f0;
            border-radius: 4px;
            margin-top: 10px;
        }

        .progress {
            height: 100%;
            border-radius: 4px;
        }

        /* 图表样式 */
        .chart-container {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .chart-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
        }

        /* 图表 */
        .chart-container {
            width: 100%;
            height: 400px;
            margin-bottom: 30px;
            border: 1px solid #ccc;
            /* 添加边框 */
            border-radius: 4px;
            /* 添加圆角 */
            padding: 10px;
            /* 添加内边距 */
        }

        #query-form {
            margin-bottom: 30px;
            display: flex;
            gap: 15px;
            align-items: center;
        }

        #query-form label {
            font-weight: bold;
        }

        #query-form button {
            padding: 8px 16px;
            background-color: #009879;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #query-form button:hover {
            background-color: #007f63;
        }
    </style>
</head>

<body>
    <div class="container">
        <form id="query-form">
            <label for="query-date">查询日期：</label>
            <input type="date" id="query-date" name="query-date" required>

            <label for="shift">查询班次：</label>
            <select id="shift" name="shift" required>
                <option value="D">白班</option>
                <option value="N">夜班</option>
            </select>
            <label for="product">产品名称：</label>
            <select id="product" name="product" required>
                {% for product in product_names %}
                <option value="{{ product }}">{{ product }}</option>
                {% endfor %}
            </select>
            

            <button type="submit">查询</button>
            <button id="save-button">保存为图片</button>
        </form>

        <!-- 添加数据汇总 -->
        <div class="pngdown">
            <div style="text-align: center; margin-bottom: 20px;">
                <h2>车间生产数据汇总</h2>
                <h3 id="query-info"></h3>
            </div>
            <div class="dashboard grid-2">

                <div class="card">
                    <div class="card-title"><i>📊</i> 总产量</div>
                    <div class="card-value" id="total-output">--</div>
                </div>

                <div class="card">
                    <div class="card-title"><i>✅</i> 正常产出</div>
                    <div class="card-value" id="normal-output">--</div>
                    <div class="card-extra">占比 <span id="normal-rate">0.00%</span></div>
                </div>

                <div class="card">
                    <div class="card-title"><i>📦</i> 平均效率</div>
                    <div class="card-value" id="avg-efficiency">0.000%</div>
                </div>

                <div class="card">
                    <div class="card-title"><i>⏱️</i> 入库效率</div>
                    <div class="card-value" id="storage-efficiency">0.000%</div>
                </div>

                <div class="card">
                    <div class="card-title"><i>🔀</i> 合并档产出</div>
                    <div class="card-value" id="merge-output">-</div>
                    <div class="card-extra">占比 <span id="merge-rate">0.000%</span></div>
                    <span>合并档位:</span><input class="hbd" value="0"></input><button class="hbdbtn">合并档更新</button>
                </div>

                <div class="card">
                    <div class="card-title"><i>⚠️</i> 漏电合并档产出</div>
                    <div class="card-value" id="leak-output">-</div>
                    <div class="card-extra">占比 <span id="leak-output-b">0.0000%</span></div>
                </div>

                <div class="card">
                    <div class="card-title"><i>🔋</i> 漏电失效产出</div>
                    <div class="card-value" id="leak-fail">-</div>
                    <div class="card-extra">占比 <span id="leak-fail-b">0.0000%</span></div>
                </div>

                <div class="card">
                    <div class="card-title"><i>💡</i> DLCC产出</div>
                    <div class="card-value" id="DL-CC">-</div>
                    <div class="card-extra">占比 <span id="DL-CC-b">0.0000%</span></div>
                </div>

            </div>

            <!-- 添加图表 -->
            <div class="chart-container" id="chart_hb1"></div>
            <div class="chart-container" id="chart_hb2"></div>
            <div class="chart-container" id="chart_hb3"></div>
            <div class="chart-container" id="chart_hb4"></div>
            <div class="chart-container" id="chart1"></div>
            <div class="chart-container" id="chart2"></div>
            <div class="chart-container" id="chart3"></div>
        </div>
    </div>

    <script>
        // 初始化 更新数据大屏
        function updateDashboard(aggtj_data, sumbin_data) {
            // 计算总产量
            const total_output = aggtj_data.reduce((sum, item) => sum + item.total_sum_ivgrade, 0);
            document.getElementById('total-output').textContent = total_output;

            // 计算正常产出
            const normal_output = aggtj_data
                .filter(item => item.Class.includes('Eta') && !item.Class.includes('Eta Fail'))
                .reduce((sum, item) => sum + item.total_sum_ivgrade, 0);
            document.getElementById('normal-output').textContent = normal_output;

            // 计算正常产出占比
            const normal_rate = ((normal_output / total_output) * 100).toFixed(2);
            document.getElementById('normal-rate').textContent = normal_rate + '%';

            // 计算平均效率
            const avg_efficiency = aggtj_data
                .filter(item => item.Class.includes('Eta'))
                .reduce((sum, item) => sum + item.total_sum_ivgrade * item.etacs, 0) / normal_output;
            const ks = aggtj_data
                .filter(item => item.Class.includes('Eta'))
                .reduce((sum, item) => sum + item.total_sum_ivgrade * item.etacs, 0)
            document.getElementById('avg-efficiency').textContent = avg_efficiency.toFixed(3) + '%';

            // 计算入库效率
            const avg_efficiency2 = aggtj_data
                .filter(item => item.Class.includes('Eta') && !item.Class.includes('Eta Fail'))
                .reduce((sum, item) => sum + item.total_sum_ivgrade * parseFloat(item.Class.replace('Eta', '')), 0) / normal_output;
            const avg_efficiency333 = aggtj_data
                .filter(item => item.Class.includes('Eta'))
            document.getElementById('storage-efficiency').textContent = avg_efficiency2.toFixed(3) + '%';

            // 计算合并档产出
            // 筛选出包含 ETA 且不包含 ETA Fail 的数据
            const etaClasses = aggtj_data.filter(item => item.Class.includes('Eta') && !item.Class.includes('Eta Fail')).sort((a, b) => {
                if (a.Class < b.Class) {
                    return -1;
                } else if (a.Class > b.Class) {
                    return 1;
                } else {
                    return 0;
                }
            });
            const merge_output = aggtj_data
                .filter(item => item.Class.includes('UNG') || item.Class.includes('IRev2-B') || item.Class.includes('Rsh-B') || item.Class.includes(etaClasses[0].Class))
                .reduce((sum, item) => sum + item.total_sum_ivgrade, 0);
            document.getElementById('merge-output').textContent = merge_output;
            document.getElementById('merge-rate').textContent = ((merge_output / total_output) * 100).toFixed(2) + '%';
            document.querySelector('.hbd').value = etaClasses[0].Class;
            

            

            // 计算漏电产出
            // 原代码尝试访问 undefined 属性，这里修正为筛选出 Class 为 'IRev2-B' 的数据并计算漏电产出
            const leak_output = aggtj_data.filter(item => item.Class === 'IRev2-B').reduce((sum, item) => sum + (item.total_sum_ivgrade || 0), 0);
            document.getElementById('leak-output').textContent = leak_output;
            document.getElementById('leak-output-b').textContent = ((leak_output / total_output) * 100).toFixed(3) + '%';

            // 计算漏电产出占比
            const leak_fail = aggtj_data.filter(item => item.Class === 'IRev2 Fail').reduce((sum, item) => sum + (item.total_sum_ivgrade || 0), 0);
            document.getElementById('leak-fail').textContent = leak_fail;
            document.getElementById('leak-fail-b').textContent = ((leak_fail / total_output) * 100).toFixed(4) + '%';

            // 计算DLCC
            // 筛选出 sumbin_data 中 binn 等于 7 的项，然后累加这些项的 quantity 属性值
            const DLCC = sumbin_data.filter(item => item.binn === 7).reduce((sum, item) => sum + item.quantity, 0);
            document.getElementById('DL-CC').textContent = DLCC;
            document.getElementById('DL-CC-b').textContent = ((DLCC / total_output) * 100).toFixed(2) + '%';
        }

        // 渲染平均入库效率折线图
        function renderAvgEfficiencyChart(all_data) {
            const chart = echarts.init(document.getElementById('chart_hb1'));
            const charthb2 = echarts.init(document.getElementById('chart_hb2'));
            const charthb3 = echarts.init(document.getElementById('chart_hb3'));
            const charthb4 = echarts.init(document.getElementById('chart_hb4'));
            // 按 date 升序，然后按 shift 升序排序
            all_data.forEach(item => {
                item.data_shift = `${item.date}-${item.shift}`;
            });

            all_data.sort((a, b) => a.data_shift.localeCompare(b.data_shift));

            // 提取数据并生成 date-shift 格式的 x 轴标签
            const xLabels = all_data.map(item => `${item.date}-${item.shift}`);
            const avg_eta = all_data.map(item => parseFloat(item.avg_eta));
            const ru_eta = all_data.map(item => parseFloat(item.ru_eta));

            //漏电合并档和漏电失效
            const IRev2_B = all_data.map(item => parseFloat(item.IRev2_B));
            const IRev2_Fail = all_data.map(item => parseFloat(item.IRev2_Fail));

            //合并档
            const hbd = all_data.map(item => parseFloat(item.hbd));
            // 计算每个合并档对应的百分比
            // 计算合并档占比
            const merge_rates = all_data.map(item => {
                // 解析合并档产出值
                const mergeOutput = parseFloat(item.hbd);
                // 解析总产量值
                const totalOutput = parseFloat(item.sum_IvGrade);
                // 如果总产量大于 0，则计算占比并保留两位小数，否则返回 0
                return totalOutput > 0 ? ((mergeOutput / totalOutput) * 100).toFixed(2) : 0;
            });
            console.log(merge_rates);
            //总数
            const total_sum_ivgrade = all_data.map(item => parseFloat(item.sum_IvGrade));
           


            //DLCC
            const dlcc = all_data.map(item => parseFloat(item.dlcc));

            //判断查询是否为当天
            // 另一种获取当天日期的方法
            const yesterday = new Date();
            const year = yesterday.getFullYear();
            const month = String(yesterday.getMonth() + 1).padStart(2, '0');
            const day = String(yesterday.getDate()).padStart(2, '0');
            date = `${year}-${month}-${day}`;
            const hour = yesterday.getHours();
            let shift = 'D';
            if (hour < 8.5) {
                yesterday.setDate(yesterday.getDate() - 1);
                console.log('当前时间小于 8.5，使用昨天的日期', yesterday);
                const year = yesterday.getFullYear();
                const month = String(yesterday.getMonth() + 1).padStart(2, '0');
                const day = String(yesterday.getDate()).padStart(2, '0');
                date = `${year}-${month}-${day}`;
                shift = 'N';
            } else if (hour > 20.5) {
                shift = 'N';
            }
            const queryDate = document.getElementById('query-date').value;
            const queryShift = document.getElementById('shift').value;
            console.log('当前时间和日期:', date, shift);
            console.log('查询的时间和日期:', queryDate, queryShift);
            if (queryDate === date && queryShift === shift) {
                // 当前时间和日期与查询的时间和日期一致
                console.log('当前时间和日期与查询的时间和日期一致');
                //获取表单数据
                hbd_value = document.getElementById('merge-output').textContent;
                sum_IvGrade_value = document.getElementById('total-output').textContent;
                avg_efficiency_value = document.getElementById('avg-efficiency').textContent;
                storage_efficiency_value = document.getElementById('storage-efficiency').textContent;
                merge_output_value = document.getElementById('merge-output').textContent;
                merge_rate_value = document.getElementById('merge-rate').textContent;
                leak_output_value = document.getElementById('leak-output').textContent;
                dlcc_value = document.getElementById('DL-CC').textContent;
                leakFailValue = document.getElementById('leak-fail').textContent;
                currentMergePercentage = (hbd_value / sum_IvGrade_value * 100).toFixed(2);
                console.log('当前查询的合并档百分比:', currentMergePercentage + '%');

                if (all_data.length >= 7) {
                    xLabels.shift();
                    avg_eta.shift();
                    ru_eta.shift();
                    IRev2_B.shift();
                    IRev2_Fail.shift();
                    hbd.shift();
                    merge_rates.shift();
                    dlcc.shift();


                }
                // 删除原数组的第一个值并添加新值
                // 原代码中的 date 变量未进行去除 - 的操作，这里假设 date 是字符串类型，使用 replace 方法去除 -
                const newDate = date.replace(/-/g, '');
                xLabels.push(`${newDate}-${shift}`);


                avg_eta.push(parseFloat(avg_efficiency_value.replace('%', '')));


                ru_eta.push(parseFloat(storage_efficiency_value.replace('%', '')));


                IRev2_B.push(parseFloat(leak_output_value));

                // 假设漏电失效值可以从某个地方获取，这里暂时用 0 代替，需要根据实际情况修改

                IRev2_Fail.push(leakFailValue);


                hbd.push(parseFloat(merge_output_value));


                merge_rates.push(currentMergePercentage);

                // 假设 DLCC 值可以从某个地方获取，这里暂时用 0 代替，需要根据实际情况修改

                dlcc.push(dlcc_value);

                console.log('更新后的 xLabels:', xLabels);
                console.log('更新后的 avg_eta:', avg_eta);
                console.log('更新后的 ru_eta:', ru_eta);
                console.log('更新后的 IRev2_B:', IRev2_B);
                console.log('更新后的 IRev2_Fail:', IRev2_Fail);
                console.log('更新后的 hbd:', hbd);
                console.log('更新后的 total_sum_ivgrade:', total_sum_ivgrade);
                console.log('更新后的 dlcc:', dlcc);
                // 计算合并档的百分比
                const mergeOutputValue = parseFloat(document.getElementById('merge-output').textContent);
                const totalSumIvGradeValue = parseFloat(document.getElementById('total-output').textContent);
                const mergePercentage = (mergeOutputValue / totalSumIvGradeValue * 100).toFixed(2);
                console.log('合并档百分比:', mergePercentage + '%');



            } else {
                // 当前时间和日期与查询的时间和日期不一致
                console.log('当前时间和日期与查询的时间和日期不一致');
            }

            // 配置平均入库效率折线图图表选项
            const option = {
                title: {
                    text: '平均入库效率趋势',
                    left: 'center',
                    top: 'top'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['平均效率', '入库效率'],
                    bottom: 'bottom'
                },
                xAxis: {
                    type: 'category',
                    data: xLabels,
                    axisLabel: {
                        rotate: -30 // 将标签倾斜 30 度
                    }
                },
                yAxis: {
                    type: 'value',
                    max: Math.max(...avg_eta) + 0.2,
                    min: Math.min(...ru_eta) - 0.2
                },
                series: [
                    {
                        name: '平均效率',
                        type: 'line',
                        smooth: true,
                        data: avg_eta,
                        label: {
                            show: true,
                            position: 'top'
                        }
                    },
                    {
                        name: '入库效率',
                        type: 'line',
                        smooth: true,
                        data: ru_eta,
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                ]
            };

            // 配置漏电合并档和漏电失效折线图图表选项
            const optionhb2 = {
                title: {
                    text: '漏电合并档和漏电失效趋势',
                    left: 'center',
                    top: 'top'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['漏电合并档', '漏电失效'],
                    bottom: 'bottom'
                },
                xAxis: {
                    type: 'category',
                    data: xLabels,
                    axisLabel: {
                        rotate: -30 // 将标签倾斜 30 度
                    }
                },
                yAxis: {
                    type: 'value',
                    max: Math.max(...IRev2_B) + 1000,
                    min: 0
                },
                series: [
                    {
                        name: '漏电合并档',
                        type: 'line',
                        smooth: true,
                        data: IRev2_B,
                        label: {
                            show: true,
                            position: 'top'
                        }
                    },
                    {
                        name: '漏电失效',
                        type: 'line',
                        smooth: true,
                        data: IRev2_Fail,
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                ]
            };

            // 配置合并档柱形图和合并档占比折线图图表选项
            const optionhb3 = {
                title: {
                    text: '合并档趋势与占比',
                    left: 'center',
                    top: 'top'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['合并档', '合并档占比'],
                    bottom: 'bottom'
                },
                xAxis: {
                    type: 'category',
                    data: xLabels,
                    axisLabel: {
                        rotate: -30 // 将标签倾斜 30 度
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '合并档数量',
                        max: Math.max(...hbd) + 1000,
                        min: 0
                    },
                    {
                        type: 'value',
                        name: '合并档占比(%)',
                        min: -0.1
                    }
                ],
                series: [
                    {
                        name: '合并档',
                        type: 'bar',
                        data: hbd,
                        label: {
                            show: true,
                            position: 'inside'
                        }
                    },
                    {
                        name: '合并档占比',
                        type: 'line',
                        yAxisIndex: 1,
                        smooth: true,
                        // 假设 merge_rate 是合并档占比数据数组
                        data: merge_rates, 
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}%'
                        }
                    }
                ]
            };

            // 配置DLCC折线图图表选项
            const optionhb4 = {
                title: {
                    text: 'DLCC趋势',
                    left: 'center',
                    top: 'top'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['DLCC'],
                    bottom: 'bottom'
                },
                xAxis: {
                    type: 'category',
                    data: xLabels,
                    axisLabel: {
                        rotate: -30 // 将标签倾斜 30 度
                    }
                },
                yAxis: {
                    type: 'value',
                    max: Math.max(...dlcc) + 1000,
                    min: 0
                },
                series: [
                    {
                        name: 'DLCC',
                        type: 'line',
                        smooth: true,
                        data: dlcc,
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                ]
            };

            // 渲染图表
            chart.setOption(option);
            charthb2.setOption(optionhb2);
            charthb3.setOption(optionhb3);
            charthb4.setOption(optionhb4);
        }

        // 处理aggregated_data，计算每个IvGrade在相同Class中的占比
        // 定义一个函数来处理数据
        function processAggregatedData(aggregatedData) {
            const etaClasses = aggregatedData ? aggregatedData.filter(item => item.Class.includes('Eta') && !item.Class.includes('Eta Fail')) : [];
            const groupedData = {};
            etaClasses.forEach(item => {
                if (!groupedData[item.Class]) {
                    groupedData[item.Class] = { total: 0, grades: {} };
                }
                groupedData[item.Class].total += item.total_sum_ivgrade;
                groupedData[item.Class].grades[item.IvGrade] = item.total_sum_ivgrade;
            });
            // 计算百分比并准备图表数据
            // 获取分组数据中的所有类别，作为图表的x轴数据
            const categories = Object.keys(groupedData).sort((a, b) => b.localeCompare(a));
            // 用于存储每个等级对应的图表数据
            // 初始化 seriesData 对象，用于存储每个等级对应的图表数据
            const seriesData = {};
            // 遍历每个类别
            categories.forEach(cls => {
                // 遍历当前类别下的所有等级
                for (const grade in groupedData[cls].grades) {
                    // 如果该等级还没有对应的图表数据数组，则初始化一个长度为类别数量的数组，并用0填充
                    if (!seriesData[grade]) {
                        seriesData[grade] = new Array(categories.length).fill(0);
                    }
                    // 获取当前类别在类别数组中的索引
                    const index = categories.indexOf(cls);
                    // 计算百分比并保留两位小数
                    seriesData[grade][index] = parseFloat(((groupedData[cls].grades[grade] / groupedData[cls].total) * 100).toFixed(2));
                }
            });
            return { categories, seriesData };
        }

        // 定义一个函数来处理 Aoi1R 数据，计算每个 Aoi1R 类别在相同 Class 中的占比
        function processAoi1RData(aggregatedData) {
            const etaClasses = aggregatedData ? aggregatedData.filter(item => item.Class.includes('Eta') && !item.Class.includes('Eta Fail')) : [];
            console.log(etaClasses);
            const groupedData = {};

            etaClasses.forEach(item => {
                if (!groupedData[item.Class]) {
                    groupedData[item.Class] = { total: 0, aoi1rCategories: {} };
                }
                groupedData[item.Class].total += item.total_sum_ivgrade;
                let aoi1rCategory;
                if (item.Aoi1R === 2) {
                    aoi1rCategory = 'DL';
                } else if (item.Aoi1R === 3) {
                    aoi1rCategory = 'L';
                } else if (item.Aoi1R === 4) {
                    aoi1rCategory = 'SL';
                } else {
                    aoi1rCategory = 'other';
                }
                if (!groupedData[item.Class].aoi1rCategories[aoi1rCategory]) {
                    groupedData[item.Class].aoi1rCategories[aoi1rCategory] = 0;
                }
                groupedData[item.Class].aoi1rCategories[aoi1rCategory] += item.total_sum_ivgrade;
            });
            // 获取分组数据中的所有类别，作为图表的 x 轴数据
            const categories = Object.keys(groupedData).sort((a, b) => b.localeCompare(a));
            // 用于存储每个 Aoi1R 类别对应的图表数据
            const seriesData = {};
            // 遍历每个类别
            categories.forEach(cls => {
                // 遍历当前类别下的所有 Aoi1R 类别
                for (const aoi1rCategory in groupedData[cls].aoi1rCategories) {
                    // 如果该 Aoi1R 类别还没有对应的图表数据数组，则初始化一个长度为类别数量的数组，并用 0 填充
                    if (!seriesData[aoi1rCategory]) {
                        seriesData[aoi1rCategory] = new Array(categories.length).fill(0);
                    }
                    // 获取当前类别在类别数组中的索引
                    const index = categories.indexOf(cls);
                    // 计算百分比并保留两位小数
                    seriesData[aoi1rCategory][index] = parseFloat(((groupedData[cls].aoi1rCategories[aoi1rCategory] / groupedData[cls].total) * 100).toFixed(2));
                }
            });
            return { categories, seriesData };
        }

        // 定义一个函数来处理第三个图表的档位占比数据
        function processChart3Data(aggregatedData) {
            const classCountMap = {};
            let totalGlass = 0;

            // 汇总 class 相同字符串的数量计数，并计算总 glass 数量
            aggregatedData.forEach(item => {
                if (classCountMap[item.Class]) {
                    classCountMap[item.Class] += item.total_sum_ivgrade;
                } else {
                    classCountMap[item.Class] = item.total_sum_ivgrade;
                }
                totalGlass += item.total_sum_ivgrade;
            });

            // 获取所有 class 名称
            const allCategories = Object.keys(classCountMap);

            // 分离包含 ETA 的数据和不包含 ETA 的数据
            const etaCategories = allCategories.filter(cls => cls.includes('Eta')).sort((a, b) => b.localeCompare(a));
            const nonEtaCategories = allCategories.filter(cls => !cls.includes('Eta')).sort((a, b) => b.localeCompare(a));

            // 合并排序后的数据
            const categories = [...etaCategories, ...nonEtaCategories];
            // 准备柱状图和折线图的数据
            const barData = [];
            const lineData = [];

            categories.forEach(cls => {
                const count = classCountMap[cls];
                barData.push(count);
                const percentage = parseFloat(((count / totalGlass) * 100).toFixed(2));
                lineData.push(percentage);
            });

            return { categories, barData, lineData };
        }

        //合并档更新
        document.querySelector('.hbdbtn').addEventListener('click', () => {
            const aggtj_data1 = JSON.parse(sessionStorage.getItem('aggtj_data1'));
            const total_output = aggtj_data1.reduce((sum, item) => sum + item.total_sum_ivgrade, 0);
            const hbdValue = document.querySelector('.hbd').value;
            const merge_output = aggtj_data1
                .filter(item => item.Class.includes('UNG') || item.Class.includes('IRev2-B') || item.Class.includes('Rsh-B') || item.Class.includes(hbdValue))
                .reduce((sum, item) => sum + item.total_sum_ivgrade, 0);
            document.getElementById('merge-output').textContent = merge_output;
            document.getElementById('merge-rate').textContent = ((merge_output / total_output) * 100).toFixed(2) + '%';
        });

        // 模拟数据
        // 表单提交事件
        document.getElementById('query-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const rawDate = document.getElementById('query-date').value;
            const dateObj = new Date(rawDate);
            const year = dateObj.getFullYear();
            const month = String(dateObj.getMonth() + 1).padStart(2, '0');
            const day = String(dateObj.getDate()).padStart(2, '0');
            const formattedDate = `${year}${month}${day}`;
            const formData = {
                query_date: formattedDate,
                shift: document.getElementById('shift').value,
                product: document.getElementById('product').value
            };

            try {
                const response = await fetch('/api/query_dwzb_eta', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                const data = await response.json();
                console.log('Received data:', data);
                // 将数据存储到 sessionStorage
                sessionStorage.setItem('aggtj_data1', JSON.stringify(data.aggtj_data));
                //调用数据大屏函数
                updateDashboard(data.aggtj_data, data.sumbin_data);
                //调用平均入库效率折线图
                renderAvgEfficiencyChart(data.all_data)

                // 更新查询信息
                document.getElementById('query-info').textContent = '查询日期：' + document.getElementById('query-date').value + ' | 班次：' + (document.getElementById('shift').value === 'D' ? '白班' : '夜班') + ' | 产品：' + document.getElementById('product').value + ' | 数据库更新时间：' + data.update_time.last_updated;

                // 调用函数
                const { categories, seriesData } = processAggregatedData(data.aggregated_data);
                // 更新图表1的数据和配置
                const gradeOrder = ['V+', 'V0', 'V-', 'V--', 'UNG', '-'];
                chart1.setOption({
                    // 设置x轴的数据为类别数组
                    xAxis: {
                        data: categories,
                        axisLabel: {
                            rotate: -30 // 将标签倾斜30度
                        }
                    },
                    // 设置y轴的配置
                    yAxis: {
                        // y轴类型为数值类型
                        type: 'value',
                        // y轴的最大值为100
                        max: 100
                    },
                    // 配置图表的系列数据
                    series: gradeOrder.filter(grade => seriesData[grade]).map(grade => ({
                        // 系列的名称为等级名称
                        name: grade,
                        // 图表类型为柱状图
                        type: 'bar',
                        // 柱状图进行堆叠
                        stack: 'total',
                        // 显示标签，格式化标签显示为百分比形式，位置在柱子内部
                        label: { show: true, formatter: '{c}%', position: 'inside' },
                        // 系列的数据为该等级对应的图表数据数组
                        data: seriesData[grade],
                        // 为每个等级指定颜色
                        itemStyle: {
                            color: {
                                'V+': '#0F7FF7',
                                'V0': '#FE9900',
                                'V-': '#50EC12',
                                'V--': '#B829E1',
                                'UNG': '#E4080A',
                                '-': '#B815E6'
                            }[grade]
                        }
                    })),
                    // 配置提示框，触发方式为坐标轴触发
                    tooltip: { trigger: 'axis' },
                    // 配置图例，图例的数据为所有等级名称
                    legend: { data: gradeOrder.filter(grade => seriesData[grade]) }
                });


                // 调用函数处理 Aoi1R 数据
                const { categories: aoi1rCategories, seriesData: aoi1rSeriesData } = processAoi1RData(data.aggaoi_data);
                // 更新图表 2 的数据和配置
                const aoi1rCategoryOrder = ['DL', 'L', 'SL', 'other'];
                chart2.setOption({
                    // 设置 x 轴的数据为类别数组
                    xAxis: {
                        data: aoi1rCategories,
                        axisLabel: {
                            rotate: -30 // 将标签倾斜 30 度
                        }
                    },
                    // 设置 y 轴的配置
                    yAxis: {
                        // y 轴类型为数值类型
                        type: 'value',
                        // y 轴的最大值为 100
                        max: 100
                    },
                    // 配置图表的系列数据
                    series: aoi1rCategoryOrder.filter(category => aoi1rSeriesData[category]).map(category => ({
                        // 系列的名称为 Aoi1R 类别名称
                        name: category,
                        // 图表类型为柱状图
                        type: 'bar',
                        // 柱状图进行堆叠
                        stack: 'total',
                        // 显示标签，格式化标签显示为百分比形式，位置在柱子内部
                        label: { show: true, formatter: '{c}%', position: 'inside' },
                        // 系列的数据为该 Aoi1R 类别对应的图表数据数组
                        data: aoi1rSeriesData[category],
                        // 为每个 Aoi1R 类别指定颜色
                        itemStyle: {
                            color: {
                                'DL': '#FF5733',
                                'L': '#33FF57',
                                'SL': '#5733FF',
                                'other': '#CCCCCC'
                            }[category]
                        }
                    })),
                    // 配置提示框，触发方式为坐标轴触发
                    tooltip: { trigger: 'axis' },
                    // 配置图例，图例的数据为所有 Aoi1R 类别名称
                    legend: { data: aoi1rCategoryOrder.filter(category => aoi1rSeriesData[category]) }
                });



                // 在表单提交事件中调用该函数并更新图表 3
                const { categories: chart3Categories, barData, lineData } = processChart3Data(data.aggregated_data);
                chart3.setOption({
                    xAxis: {
                        data: chart3Categories,
                        axisLabel: {
                            rotate: -30 // 将标签倾斜 30 度
                        }
                    },
                    yAxis: [
                        { type: 'value', name: '数量' },
                        { type: 'value', name: '百分比', max: 100 }
                    ],
                    series: [
                        {
                            name: '数量',
                            type: 'bar',
                            data: barData,
                            yAxisIndex: 0,
                            label: { show: true, position: 'top' }
                        },
                        {
                            name: '百分比',
                            type: 'line',
                            data: lineData,
                            yAxisIndex: 1,
                            label: { show: true, formatter: '{c}%', position: 'top' }
                        }
                    ],
                    tooltip: { trigger: 'axis' },
                    legend: { data: ['数量', '百分比'] }
                });
                // 更新图表数据
                mockData.chart1.series[0].data = data.chart1?.series1 || [];
                mockData.chart1.series[1].data = data.chart1.series2;
                mockData.chart2.series[0].data = data.chart2.series1;
                mockData.chart2.series[1].data = data.chart2.series2;
                mockData.chart3.barSeries = data.chart3.barSeries;
                mockData.chart3.lineSeries = data.chart3.lineSeries;

                // 更新图表
                chart1.setOption({ series: mockData.chart1.series });
                chart2.setOption({ series: mockData.chart2.series });
                chart3.setOption({
                    series: [
                        { data: mockData.chart3.barSeries },
                        { data: mockData.chart3.lineSeries }
                    ]
                });

                // 更新时间显示
                document.getElementById('update-time').textContent = '最后更新时间：' + new Date().toLocaleString();
            } catch (error) {
                console.error('Error:', error);
            }
        });




        // 初始化图表
        const chart1 = echarts.init(document.getElementById('chart1'));
        const chart2 = echarts.init(document.getElementById('chart2'));
        const chart3 = echarts.init(document.getElementById('chart3'));

        // 自动填充日期和班次
        function autoFillForm() {
            const now = new Date();
            const hours = now.getHours();
            const minutes = now.getMinutes();
            const currentTime = hours * 60 + minutes;

            let date = new Date();
            let shift = 'D';

            if (currentTime >= 0 && currentTime < 510) { // 00:00-08:30
                date.setDate(date.getDate() - 1);
                shift = 'N';
            } else if (currentTime >= 510 && currentTime < 1230) { // 08:30-20:30
                shift = 'D';
            } else { // 20:30-24:00
                shift = 'N';
            }

            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const formattedDate = `${year}-${month}-${day}`;

            document.getElementById('query-date').value = formattedDate;
            document.getElementById('shift').value = shift;
        }

        // 页面加载时调用
        autoFillForm();

        // 添加保存图片功能
        document.getElementById('save-button').addEventListener('click', () => {
            saveClassAsImage('pngdown')
        });
        // 配置图表1
        chart1.setOption({
            title: {
                text: '开压占比',
                left: 'center'
            },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: [] },
            yAxis: { type: 'value', max: 1 },
            series: [],
            legend: { data: [], bottom: 0 }
        });

        // 配置图表2
        chart2.setOption({
            title: {
                text: '颜色占比',
                left: 'center'
            },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: [] },
            yAxis: { type: 'value', max: 1 },
            series: [],
            legend: { data: [], bottom: 0 }
        });

        // 配置图表3
        chart3.setOption({
            title: {
                text: '档位占比',
                left: 'center'
            },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: [] },
            yAxis: [{ type: 'value', name: '柱状图' }, { type: 'value', name: '折线图' }],
            series: [],
            legend: { data: [], bottom: 0 }
        });

        // 移除模拟数据
        const mockData = null;

        // 配置图表1
        chart1.setOption({
            title: {
                text: '开压占比',
                left: 'center' // 标题居中
            },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: mockData.chart1.categories },
            yAxis: { type: 'value', max: 1 },
            series: mockData.chart1.series.map(s => ({
                ...s,
                type: 'bar',
                stack: 'total',
                label: { show: true, position: 'inside' }
            })),
            legend: {
                data: mockData.chart1.series.map(s => s.name),
                bottom: 0 // 图例放在图表下方
            }
        });

        // 配置图表2
        chart2.setOption({
            title: {
                text: '颜色占比',
                left: 'center' // 标题居中
            },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: mockData.chart2.categories },
            yAxis: { type: 'value', max: 1 },
            series: mockData.chart2.series.map(s => ({
                ...s,
                type: 'bar',
                stack: 'total',
                label: { show: true, position: 'inside' }
            })),
            legend: {
                data: mockData.chart2.series.map(s => s.name),
                bottom: 0 // 图例放在图表下方
            }
        });

        // 配置图表3
        chart3.setOption({
            title: {
                text: '档位占比',
                left: 'center' // 标题居中
            },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: mockData.chart3.categories },
            yAxis: [{ type: 'value', name: '柱状图' }, { type: 'value', name: '折线图' }],
            series: [
                {
                    name: '柱状图',
                    type: 'bar',
                    data: mockData.chart3.barSeries
                },
                {
                    name: '折线图',
                    type: 'line',
                    yAxisIndex: 1,
                    data: mockData.chart3.lineSeries
                }
            ],
            legend: {
                data: ['柱状图', '折线图'],
                bottom: 0 // 图例放在图表下方
            }
        });
    </script>
</body>

</html>